<template>
  <el-col :span="18">
    <div class="banner flex justify-between items-center px-10">
      <span class="group-name text-secondary">
        {{ $t('flyparam.param_app') }}
        <br />
        <h1 style="font-size: 1.5em; font-weight: 700; color: #ffffff">
          {{ info.appName }}
        </h1>
      </span>
      <div class="text-right">
        <el-dropdown v-if="!noData" @command="handlePreviewCommand">
          <span class="el-dropdown-link">
            <svg-icon
              icon-class="eye-open"
              class="mr-5 text-2xl icon-eye"
              style="color: white"
            />
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="dataPreview">
                <div class="flex items-center">
                  <svg-icon icon-class="file-zip" class="mr-[5]" />{{
                    $t('flyparam.data_preview')
                  }}
                </div>
              </el-dropdown-item>
              <el-dropdown-item command="confPagePreview">
                <div class="flex items-center">
                  <svg-icon icon-class="web-page" class="mr-[5]" />{{
                    $t('flyparam.page_preview')
                  }}
                </div>
              </el-dropdown-item>
            </el-dropdown-menu></template
          >
        </el-dropdown>
        <el-tooltip
          v-if="!noData"
          content="Param Template Design"
          placement="top"
        >
          <button
            v-permission="{
              permission: [PERMISSIONS.DESIGN, PERMISSIONS.PERMISSION_CONTROL]
            }"
            @click="design"
          >
            <svg-icon icon-class="template_design" class="text-2xl mr-2" />
          </button>
        </el-tooltip>
      </div>
    </div>
    <div v-if="noData == true">
      <div class="no-data">
        <p>
          {{ this.$t('flyparam.template_no_configure_tip1') }}.
          {{ $t('flyparam.click') }}
          <a class="link" @click="() => this.$emit('edit', info)">{{
            $t('flyparam.design')
          }}</a
          >&nbsp;{{ $t('flyparam.start_configure_tip') }}.
        </p>
      </div>
    </div>
    <div v-else-if="noData == false" class="px-7 py-5">
      <app-info :info="info" @confirm="fetchData" />
    </div>

    <preview-drawer
      ref="previewDrawer"
      size="60%"
      v-model="jsonDrawerVisible"
      :content="jsonStr"
      :file-type="previewDrawerFileType"
      :loading="previewDrawerLoading"
      @refresh="(fileType) => previewTemplate(fileType)"
    />

    <el-dialog
      class="configuration-preview-dialog"
      :title="$t('flyparam.page_preview')"
      v-model="configPreviewDialogVisible"
      width="80%"
    >
      <configuration-preview :info="info" :layout="layout" />
    </el-dialog>
  </el-col>
</template>

<script>
import {
  getParameterTemplatePreview,
  getTemplateTableLayoutList,
  getParameterTemplateInfo,
  getReferenceTable
} from '@/api/parameter'
import base64 from '@/utils/base64'
import AppInfo from './app-info.vue'
import PreviewDrawer from './components/preview-drawer'
import ConfigurationPreview from './components/configuration-preview.vue'
import { mapLayoutData } from './helper'
import { PERMISSIONS } from '@/components/common/const'

var formatXml = require('xml-formatter')

export default {
  name: 'FlyParameter',
  components: {
    AppInfo,
    PreviewDrawer,
    ConfigurationPreview
  },
  provide() {
    return {
      devCount: 0
    }
  },
  data() {
    return {
      PERMISSIONS: { ...Object.freeze(PERMISSIONS.FLY_PARAM) },
      noData: undefined,
      dialogVisible: false,
      info: { id: '' },
      jsonDrawerVisible: false,
      configPreviewDialogVisible: false,
      jsonStr: '', // 预览的json数据
      previewDrawerFileType: 1,
      previewDrawerLoading: false,
      layout: []
    }
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    // 弹窗点击确认后的回调
    handleConfirm() {},
    // 关闭窗口的回调
    handleClose() {},
    design() {
      this.$router.push(`/flyparameter/config/${this.$route.params.id}`)
    },
    fetchData() {
      getParameterTemplateInfo(this.$route.params.id).then((res) => {
        this._provided.devCount = res.devCount
        this.noData = res.status === 0
        this.info = res
        this.$store.commit('parameter/SET_APP_NAME', res.appName)
        this.$store.commit('parameter/SET_NEW_TEMPLATE', res)
        this.fetchLayout()
      })
    },
    fetchLayout() {
      getTemplateTableLayoutList(this.$route.params.id, this.info.entryId).then(
        async (data) => {
          const referenceTables = await this.fetchReferenceTable()
          this.layout = data.map((item) => {
            return mapLayoutData.call(this, item, referenceTables)
          })
        }
      )
    },
    fetchReferenceTable() {
      return new Promise((resolve, reject) => {
        this.selectLoading = true
        getReferenceTable(this.$route.params.id, this.info.entryId)
          .then((data) => {
            resolve(data)
          })
          .catch((err) => {
            reject(err)
          })
          .finally(() => {
            this.selectLoading = false
          })
      })
    },
    handlePreviewCommand(command) {
      if (command === 'confPagePreview') {
        this.configPreviewDialogVisible = true
      } else if (command === 'dataPreview') {
        this.previewTemplate(this.info.fileType)
      }
    },
    previewTemplate(fileType) {
      this.jsonDrawerVisible = true
      this.previewDrawerFileType = fileType
      this.previewDrawerLoading = true
      getParameterTemplatePreview(this.$route.params.id, fileType).then(
        (data) => {
          this.previewDrawerLoading = false
          if (fileType === 1) {
            const decoded = base64.decode(data.previewData) || '{}'
            this.jsonStr = JSON.parse(decoded)
          } else if (fileType === 2) {
            this.jsonStr = data.previewData
            this.$refs.previewDrawer.decode(data.previewData)
          } else if (fileType === 3) {
            const xml = base64.decode(data.previewData)
            this.jsonStr = formatXml(xml, {
              indentation: '  ',
              filter: (node) => node.type !== 'Comment',
              collapseContent: true,
              lineSeparator: '\n'
            })
          }
        }
      )
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/mixin.scss';

.no-data {
  margin-top: 150px;

  width: 100%;

  p {
    width: 600px;
    margin: 0 auto;
    font-size: 18px;
    line-height: 80px;
    color: #7e7e7e;
    text-align: center;
  }

  .link {
    font-weight: bold;
    text-decoration: underline;
    color: #409eff;
  }
}

.configuration-preview-dialog::v-deep {
  .el-dialog__body {
    padding: 10px 20px;
  }
}
</style>
